#!/bin/bash

set -e

if [[ $# < 1 || $# == 1 && "$1" == '--help' ]]; then
    echo -e "Usage:\n  $0 <blade-target-name> [build arguments]"
    exit 1;
fi

target_pattern=":[A-Za-z0-9+_.-]+$"

if [[ ! "$1" =~ $target_pattern ]]; then
    echo "Invalid target name, can only be :name"
    exit 1;
fi

# :poppy -> poppy
name=${1/:/}

blade build $@
source `dirname $0`/bladefunctions
wd=`pwd`
root=`_find_project_root`
relwd="${wd/${root}/}"

o=`blade query "$1" --deps`
cd $root

libname="$wd/lib${name}.a"
rm -f "$libname"
ar -q "$libname"
macname="merge-$$.mac"
echo "OPEN $libname" > $macname
echo "ADDLIB blade-bin$relwd/lib$name.a" >> $macname

libpattern="^[A-Za-z0-9+_./-]+:[A-Za-z0-9+_.-]+$"
syslibpattern="^.+"

echo "$o" | while read line; do
    if [[ "$line" =~ $libpattern ]]; then
        lib="blade-bin/${line/://lib}.a"
        echo "ADDLIB $lib"
        echo "ADDLIB $lib" >> $macname
    else
        if [[ -n "$line" ]]; then
            if [[ "$line" =~ $syslibpattern ]]; then
                echo -e "\033[1;33m$line is a system library and then can't be merged,"\
                    "don't forget to link it\033[m"
            else
                echo -e "\033[1;33mIgnore unknown libname: $line\033[m"
            fi
        fi
    fi
done
echo "SAVE" >> $macname
echo "END" >> $macname

ar -M < $macname
ranlib $libname
# rm $macname
echo "$libname generated"
